package cn.itcast.bos.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
@ParentPackage("json-default")
@Namespace("/")
@Actions
@Controller
@Scope("prototype")
public class AreaAction extends BaseAction<Area>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * 注入service
	 * @return
	 */
	@Autowired
	private AreaService areaService;
	
	@Action(value="area_save",results={@Result(name="save",type="redirect",location="./pages/base/area.html")})
	public String save(){
		areaService.save(model);
		return "save";
	}
	
	@Action(value="area_pageQuery",results={@Result(name="json",type="json")})
	public String pageQuery(){
		//有条件分页查询
		PageRequest pageable = new PageRequest(page -1, rows);
		
		Specification<Area> specification =  new Specification<Area>() {

			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				
				//predicate拼装查询条件
				Predicate predicate = null;
				
				List<Predicate> list = new ArrayList<Predicate>();
				
				//省份
				if (StringUtils.isNotBlank(model.getProvince())) {
					Predicate p = cb.like(root.get("province").as(String.class),"%"+ model.getProvince()+"%");
					list.add(p);
				}
				
				//城市
				if (StringUtils.isNotBlank(model.getCity())) {
					Predicate p =cb.like(root.get("city").as(String.class), "%"+model.getCity()+"%");
					list.add(p);
				}
				//区(县)
				if (StringUtils.isNotBlank(model.getDistrict())) {
					Predicate p = cb.like(root.get("district").as(String.class), "%"+model.getDistrict()+"%");
					list.add(p);
				}
				
				//构建条件的组合
				if (list!=null&&list.size()>0) {
					//构建一个数组
					Predicate p [] = new Predicate[list.size()];
					
					predicate = cb.and(list.toArray(p));
				}
				
				return predicate;
			}
		};
		
		Page<Area> pageDate = areaService.findPageQueryByCondition(specification,pageable);
		
		super.pushPageDataToValueStack(pageDate);
		return "json";
	}
	
	@Action(value="area_deleteArea",results={@Result(name="deleteSuccess",type="redirect",location="./pages/base/area.html")})
	public String deleteArea(){
		areaService.deleteArea(ids);
		return "deleteSuccess";
	}
	
	private File file;
	private String fileFileName;
	private String fileContentType;
	public void setFile(File file) {
		this.file = file;
	}
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	
	
	@Action(value="area_batchImport",results={@Result(name="batchImport",type="redirect",location="./pages/base/area.html")})
	public String batchImport() throws Exception{
		//1.创建一个集合用来存储区域
		List<Area> areas = new ArrayList<Area>();
		
		//2.加载execal文件对象
		
		HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
		
		//3.读取一个sheet表
		HSSFSheet sheet = wb.getSheetAt(0);
		
		//4.读取表中的每一行,一行数据,对应一个区域对象
		for (Row row : sheet) {
			//5.如果是第一行,表头就跳过
			if (row.getRowNum() == 0) {
				continue;
			}
			
			//6.跳过空值的行,要求此行作废
			if (row.getCell(0)==null||StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				continue;
			}
			
			//7.创建area对象,给对象赋值,并将该对象添加到list集合中
			Area a = new Area();
			a.setId(row.getCell(0).getStringCellValue());//区域编号
			a.setProvince(row.getCell(1).getStringCellValue());//省份
			a.setCity(row.getCell(2).getStringCellValue());//城市
			a.setDistrict(row.getCell(3).getStringCellValue());//区域
			a.setPostcode(row.getCell(4).getStringCellValue());//邮编
			
			String province = a.getProvince();
			String city = a.getCity();
			String district = a.getDistrict();
			
			province = province.substring(0, province.length()-1);//去掉省
			city = city.substring(0, city.length()-1);//去掉市
			district = district.substring(0, district.length()-1);//去掉县,区
			
			String[] headArray = PinYin4jUtils.getHeadByString(province+city+district);
			StringBuilder sb = new StringBuilder();
			for (String str : headArray) {
				sb.append(str);
			}
			
			//设置城市简码
			a.setShortcode(sb.toString());
			
			//设置城市编码
			a.setCitycode(PinYin4jUtils.hanziToPinyin(city,""));
			
			areas.add(a);
			
		}
		//8.调用业务层导入添加
		areaService.saveAreas(areas);
		
		return "batchImport";
	}
}
